package com.doupi.partner.op.controller.configure;

import com.doupi.partner.dal.model.Administrator;
import com.doupi.partner.dal.model.AdministratorHasRole;
import com.doupi.partner.dal.model.AdministratorRole;
import com.doupi.partner.manager.authenticator.util.PasswordUtils;
import com.doupi.partner.service.AdministratorHasRoleService;
import com.doupi.partner.service.AdministratorRoleService;
import com.doupi.partner.service.AdministratorService;
import com.doupi.partner.service.dto.AdministratorDto;
import com.doupi.partner.util.AjaxResponse;
import com.doupi.partner.util.DataTableData;
import com.doupi.partner.util.ObjectUtils;
import com.doupi.partner.util.Pagination;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("configure/administrator")
public class AdministratorController {

	private final static String TEMPLATE_FOLDER = "configure/";

	private final AdministratorService administratorService;

	private final AdministratorHasRoleService administratorHasRoleService;

	private final AdministratorRoleService administratorRoleService;

	@Autowired
	public AdministratorController(AdministratorService administratorService, AdministratorHasRoleService administratorHasRoleService, AdministratorRoleService administratorRoleService) {
		this.administratorService = administratorService;
		this.administratorHasRoleService = administratorHasRoleService;
		this.administratorRoleService = administratorRoleService;
	}

	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index() {
		return TEMPLATE_FOLDER + "administrator/index";
	}

	@ResponseBody
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public DataTableData<Administrator> list(Integer offset, Integer limit, Administrator administrator) {
		Pagination<Administrator, Administrator> pagination = new Pagination<>(offset, limit, administrator);
		pagination = administratorService.queryAdministrators(pagination);
		List<Administrator> lists = new ArrayList<>();

		// 查询管理员角色
		for (Administrator admin : pagination.getRecords()) {
			AdministratorDto administratorDto = new AdministratorDto();
			ObjectUtils.copyProperties(administratorDto, admin);
			// 1.查询管理员-角色对应关系
			List<AdministratorHasRole> temps = administratorHasRoleService.queryByAdministratorId(administratorDto.getId());
			List<AdministratorRole> administratorRoles = new ArrayList<>();
			// 2.循环1查询的集合，根据角色ID查询角色
			for (AdministratorHasRole temp : temps) {
				AdministratorRole administratorRole = administratorRoleService.selectByPrimaryKey(temp.getAdministratorRoleId());
				administratorRoles.add(administratorRole);
			}
			administratorDto.setAdministratorRoles(administratorRoles);
			lists.add(administratorDto);
		}
		return new DataTableData<>(pagination.getTotalCount(), lists);
	}

	@ResponseBody
	@RequestMapping(value = "delete/{id}", method = RequestMethod.DELETE)
	public AjaxResponse delete(@PathVariable("id") Long id) {
		administratorService.deleteByPrimaryKey(id);
		return AjaxResponse.defaultResponse();
	}

	@RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
	public String edit(ModelMap modelMap, @PathVariable(value = "id") Long id) {
		Administrator administrator = administratorService.selectByPrimaryKey(id);
		modelMap.put("administrator", administrator);

		// 1.查询所有可用角色，用于前端展示
		AdministratorRole administratorRole = new AdministratorRole();
		administratorRole.setStatus(Byte.valueOf("1"));
		modelMap.put("administratorRoles", administratorRoleService.queryAdministratorRoles(administratorRole, new RowBounds(0, Integer.MAX_VALUE)));

		// 2.如果是编辑则查询该用户对应的角色
		if (null != administrator) {
			modelMap.put("administratorHasRoles", administratorHasRoleService.queryByAdministratorId(administrator.getId()));
		}
		return TEMPLATE_FOLDER + "administrator/edit";
	}

	@Transactional
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(ModelMap modelMap, AdministratorDto administratorDto) {
		// 1.判断手机号是否已经存在
		Administrator administratorByMobile = administratorService.selectByMobile(administratorDto.getMobile());
		if (null != administratorByMobile && !administratorDto.getId().equals(administratorByMobile.getId())) {
			modelMap.put("administrator", administratorDto);
			modelMap.put("errorMessage", "手机号已经存在");
			return "redirect:edit";
		}

		// 2.如果设置了密码，则对密码加密，否则不更新密码
		if (StringUtils.isNotBlank(administratorDto.getPassword())) {
			String passwordSalt;
			if (null != administratorByMobile) {
				passwordSalt = administratorByMobile.getPasswordSalt();
			} else {
				passwordSalt = PasswordUtils.generatePasswordSalt();
				administratorDto.setPasswordSalt(passwordSalt);
			}
			administratorDto.setPassword(PasswordUtils.encryptPassword(administratorDto.getPassword(), passwordSalt));
		} else {
			administratorDto.setPassword(null);
		}

		administratorService.saveAdministrator(administratorDto);
		return "redirect:index";
	}
}
